package com.cheng.spider.analyze;

import com.cheng.spider.constant.MimeType;
import org.apache.http.HttpResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public abstract class AbstractResponseAnalyzer implements ResponseAnalyzer {

    private static final Logger LOGGER = LoggerFactory.getLogger(AbstractResponseAnalyzer.class);

    private StatusCodeResolver statusCodeResolver;

    private MimeTypeMatcher mimeTypeMatcher;

    public AbstractResponseAnalyzer() {
        statusCodeResolver = initStatusCodeResolver();
        mimeTypeMatcher = initMimeTypeMatcher();
    }

    @Override
    public MimeType analyze(HttpResponse response) {
        MimeType mimeType;

        //检查状态码,未受理的状态码则抛出UnsupportedStatusCodeException异常
        statusCodeResolver.check(response);

        //判断MIME类型，未处理的类型会抛出UnsupportedMimeException异常
        mimeType = mimeTypeMatcher.matches(response);

        //根据MIME类型处理响应体
        return mimeType;
    }

    protected abstract StatusCodeResolver initStatusCodeResolver();

    protected abstract MimeTypeMatcher initMimeTypeMatcher();
}
